import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms';

export function getControls(target: FormArray | FormGroup): FormItem[] {
  if (target instanceof FormArray) {

    return target.controls.map((control, i) => {
      if (control instanceof FormGroup) {
        return {
          key: `${i}`, type: 'group', group: control,
        };
      }
      else if (control instanceof FormArray) {
        return {
          key: `${i}`, type: 'array',
          array: control,
          controls: getControls(control)
        };
      }
      else {
        return { key: `${i}`, type: 'control', control: <FormControl>control };
      }
    });
  }
  else if (target instanceof FormGroup) {
    return Object.keys(target.controls).map(key => {
      const control = target.controls[key];

      if (control instanceof FormGroup) {
        return {
          key, type: 'group',
          group: control,
        };
      }
      else if (control instanceof FormArray) {
        return {
          key, type: 'array',
          array: control,
          controls: getControls(control)
        };
      }
      else {
        return { key, type: 'control', control: <FormControl>control };
      }
    });
  }
  return [];
}


export type FormGroupItem = {
  key: string,
  type: "group",
  group: FormGroup,
};
export type FormArrayItem = {
  key: string,
  type: "array",
  array: FormArray,
};
export type FormControlItem = {
  key: string,
  type: "control",
  control: AbstractControl;
};

export type FormItem = FormGroupItem | FormArrayItem | FormControlItem;